﻿using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sync_signal_light.subs
{
    public static class opini
    {

        public static List<string> ls_com_info = new List<string>();
        public static Dictionary<int,cls_device> DicDevs = new Dictionary<int, cls_device>();//设备列表
        public static int AlarmCode {  get; set; }=0;//报警代码
        public static int AlarmLose { get; set; }=0;//
        public static cls_config CLS_CFG {  get; set; }= new cls_config();//配置类
        public static cls_parameters CLS_PARA { get; set; } = new cls_parameters();//参数类
        public static cls_alarm_control CLS_ALARM { get; set; } = new cls_alarm_control();//报警控制类

        private static string iPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Config.ini";
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        public static List<string> comm_info = new List<string>();

        public static void cprint(string info)
        {
            string infos = string.Format("{0} {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), info.Replace("\r", "").Replace("\n", ""));
            Console.WriteLine(infos);
            ls_com_info.Add(infos);
            if (ls_com_info.Count > 50000) ls_com_info.Clear();
        }
        public static string read_config(string iItems, string iKey)
        {
            return NodeRead(iPath, iItems, iKey);
        }
        public static void write_config(string iItems, string iKey, string iValue)
        {
            NodeWrite(iPath, iItems, iKey, iValue);
        }
        #region //读取关键字
        public static string NodeRead(string FilePath, string Section, string Key)
        {
            Console.WriteLine(string.Format("write:path={0},section={1},key={2}", FilePath, Section, Key));
            try
            {
                StringBuilder retVal = new StringBuilder(0xFFFF);
                if (!File.Exists(FilePath))
                {
                    FileStream FS = new FileStream(FilePath, FileMode.CreateNew);
                    FS.Close();
                    NodeWrite(FilePath, Section, Key, "");
                    return Key;
                }
                else
                {
                    int num = GetPrivateProfileString(Section, Key, "", retVal, 0xffff, FilePath);
                    if (num > 0)
                    {
                        return retVal.ToString();
                    }
                    else
                    {
                        NodeWrite(FilePath, Section, Key, "");
                        return Key;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region  //修改关键字        
        private static object LockerIni = new object();
        public static void NodeWrite(string FilePath, string Section, string Key, string Value)
        {
            try
            {
                Console.WriteLine(string.Format("write:path={0},section={1},key={2},value={3}", FilePath, Section, Key, Value));
                if (!File.Exists(FilePath))
                {
                    FileStream FS = new FileStream(FilePath, FileMode.CreateNew);
                    FS.Close();
                }
                else
                {
                    lock (LockerIni) { WritePrivateProfileString(Section, Key, Value, FilePath); }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 写入本机log
        private static object LockerTxt = new object();
        private static string Ppath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\logs\\";
        public static void clogs(string wStr)
        {
            try
            {
                if (Directory.Exists(Ppath) == false) //如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(Ppath);
                }
                lock (LockerTxt)
                {
                    Console.WriteLine($"COM:{wStr}");
                    File.AppendAllText(Ppath + "C" + DateTime.Now.ToString("yyyyMMdd") + ".log", "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "-->" + "\t" + wStr);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public static void elogs(string wStr)
        {
            try
            {

                if (Directory.Exists(Ppath) == false) //如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(Ppath);
                }
                lock (LockerTxt)
                {
                    Console.WriteLine("Error:" + wStr);
                    File.AppendAllText(Ppath + "E" + DateTime.Now.ToString("yyMMdd") + ".log", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + ":" + wStr + "\r\n");
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        #endregion

        #region 将16进制字符串转化成byte数组
        public static byte[] StringToByteArray(string hexString)
        {
            try
            {
                hexString = hexString.Replace(" ", "");
                if ((hexString.Length % 2) != 0) hexString += " ";
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 将byte数组转化成16进制字符串
        public static string HexArrayToString(byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++) strB.Append(bytes[i].ToString("X2") + " ");
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion

        #region //byte[] to float
        public static float bytes2float(byte[] bytes)
        {
            byte[] intBuffer = new byte[4];
            intBuffer[0] = bytes[3];
            intBuffer[1] = bytes[2];
            intBuffer[2] = bytes[1];
            intBuffer[3] = bytes[0];
            return BitConverter.ToSingle(intBuffer, 0);
        }
        #endregion

    }
    public static class SQLiteHelper
    {
        private static string _connectionString;
        private static string dbpathstring = System.Environment.CurrentDirectory + "\\cfg_dbs.db";
        public static void com_string()
        {
            _connectionString = $"Data Source={dbpathstring};Version=3;";
        }
        public static void InitializeDatabase()
        {
            _connectionString = $"Data Source={dbpathstring};Version=3;";
            // 如果数据库文件不存在则自动创建
            if (!File.Exists(dbpathstring))
            {
                //SqliteConnection.CreateFile(dbpathstring);
            }
            using (var connection = new SqliteConnection(_connectionString))
            {
                connection.Open();

                // 创建示例表（如果不存在）
                CreatorDevices();
                CreatorSerials();
                CreatorTactics();
                //connection.Close();
            }
        }

        // 执行非查询SQL语句
        public static int ExeNonQuery(string sql)
        {
            using (var connection = new SqliteConnection(_connectionString))
            using (var command = new SqliteCommand(sql, connection))
            {
                connection.Open();
                int res = command.ExecuteNonQuery();
                //connection.Close();
                return res;
            }
        }
        //DELETE操作会保留表结构、索引、触发器等，但不会重置自增计数器
        //如果需要重置自增计数器，可以执行：DELETE FROM sqlite_sequence WHERE name='tableName'
        // 查询数据
        public static DataTable ExeQuery(string sql)
        {
            using (var connection = new SqliteConnection(_connectionString))
            using (var command = new SqliteCommand(sql, connection))
            {
                connection.Open();
                using (SqliteDataReader reader = command.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    //connection.Close();
                    return dt;
                }
            }
        }
        private static void CreatorDevices()
        {
            string sql = @"
                CREATE TABLE IF NOT EXISTS devices (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    room TEXT NOT NULL,
                    addr TEXT NOT NULL,
                    type TEXT NOT NULL,
                    superior TEXT NOT NULL,
                    port TEXT NOT NULL, 
                    relay TEXT 
                )";
            ExeNonQuery(sql.Replace("\r\n", ""));
        }
        private static void CreatorSerials()
        {
            string sql = @"
                CREATE TABLE IF NOT EXISTS serials (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    type TEXT NOT NULL,
                    port TEXT NOT NULL,
                    baud TEXT NOT NULL,
                    datas TEXT NOT NULL,
                    [check] TEXT NOT NULL,
                    stops TEXT NOT NULL 
                )";
            ExeNonQuery(sql.Replace("\r\n", ""));
        }
        private static void CreatorTactics()
        {
            string sql = @"
                CREATE TABLE IF NOT EXISTS tactics (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    type TEXT NOT NULL,
                    times TEXT NOT NULL,
                    light INTEGER NOT NULL,
                    basic INTEGER NOT NULL,
                    streng INTEGER NOT NULL,
                    sate INTEGER NOT NULL,
                    note TEXT
                )";
            ExeNonQuery(sql.Replace("\r\n", ""));
        }

        
    }

    public class cls_alarm_control
    {
        public List<byte> open_light { get; set; } = new List<byte>() { 0xFF, 0x06, 0x00, 0x01, 0x00, 0x00, 0xCD, 0xD4 };//打开报警器灯光
        public List<byte> open_beer { get; set; } = new List<byte>() { 0xFF, 0x06, 0x00, 0x01, 0x00, 0x00, 0xCD, 0xD4 };//打开报警器蜂鸣器
        public List<byte> close_light { get; set; } = new List<byte>() { 0xFF, 0x06, 0x00, 0x16, 0x00, 0x01, 0xBC, 0x10 };//关闭报警器灯光
        public List<byte> close_beer { get; set; } = new List<byte>() { 0xFF, 0x06, 0x00, 0x16, 0x00, 0x01, 0xBC, 0x10 };//关闭报警器蜂鸣器
    }
    public class cls_config
    { 
        public List<string> addrs {  get; set; }= new List<string>() { "1","2","3","4","5"};//
        public string alarm_port { get; set; } = "COM1";//报警串口
        public string light_port { get; set; } = "COM3";//灯控串口
        public int alarm_delay { get; set; } = 3000;//延时 ms
        public int light_delay { get; set; } = 200;//延时 ms
        public bool start_enable { get; set; } = false;//启动使能
        public bool sync_enable {  get; set; }= false;//总线同步
        public int sync_delay { get; set; } = 1000;//总线同步延时 ms

    }
    public class cls_writes
    { 
        public byte address { get; set; } = 1;//设备地址
        public int reister { get; set; } = 0;//寄存器
        public int value { get; set; } = 0;//值
    }
    public class cls_parameters
    { 
        public bool update { get; set; } = false;//是否更新
        public bool auto { get; set; } = false;//是否自动
        public List<cls_writes> cwt { get; set; } = new List<cls_writes>();//写入列表
    }
    public class cls_device
    {
        public int light_level { get; set; } = 0;//亮度阈值
        public int light_now { get; set; } = 0;//当前亮度
        public bool check { get; set; } = false;//选择状态
        public int day_enable { get; set; } = 1;//白天使能
        public int day_light { get; set; } = 100;//白天亮度
        public int day_cycle { get; set; } = 0;//白天闪烁周期
        public int day_delay { get; set; } = 0;//白天闪烁延时
        public int night_enable { get; set; } = 1;//夜晚使能
        public int night_light { get; set; } = 100;//夜晚亮度
        public int night_cycle { get; set; } = 0;//夜晚闪烁周期
        public int night_delay { get;set; } = 0;//夜晚闪烁延时
        public int gps_count { get; set; } = 0;//通信次数
        public string status { get; set; } = "正常";//状态
    }


}
